package me.zhengjie.spider.pool;

import me.zhengjie.config.FileProperties;
import me.zhengjie.spider.util.service.FileDownloader;
import me.zhengjie.utils.SpringContextHolder;
import org.apache.commons.pool2.DestroyMode;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.springframework.web.client.RestTemplate;

/**
 * 获取FileDownloader的工厂类
 *
 * @author Administrator
 */
public class DownloaderObjectFactory implements PooledObjectFactory<FileDownloader> {

    private RestTemplate restTemplate;
    private FileProperties fileProperties;

    public DownloaderObjectFactory(RestTemplate rt, FileProperties fp) {
        restTemplate = rt;
        fileProperties = fp;
    }

    /**
     * 激活一个对象，使其可用用
     *
     * @param pooledObject 池化对象
     * @throws Exception 异常
     */
    @Override
    public void activateObject(PooledObject<FileDownloader> pooledObject) throws Exception {
        pooledObject.getObject().setIsActive(true);
    }

    /**
     * 销毁对象
     *
     * @param pooledObject 池化对象
     * @throws Exception 异常
     */
    @Override
    public void destroyObject(PooledObject<FileDownloader> pooledObject) throws Exception {
        pooledObject.getObject().setIsActive(false);
    }

    /**
     * 销毁对象
     *
     * @param pooledObject 池化对象
     * @param destroyMode  销毁模式
     * @throws Exception 异常
     */
    @Override
    public void destroyObject(PooledObject<FileDownloader> pooledObject, DestroyMode destroyMode) throws Exception {
        pooledObject.getObject().setIsActive(false);
        PooledObjectFactory.super.destroyObject(pooledObject, destroyMode);
    }

    /**
     * 构造一个封装对象
     *
     * @throws Exception 异常
     */
    @Override
    public PooledObject<FileDownloader> makeObject() throws Exception {
//        FileDownloader bean = SpringContextHolder.getBean(FileDownloader.class);
        FileDownloader bean = new FileDownloader();
        bean.setFileProperties(fileProperties);
        bean.setRestTemplate(restTemplate);
        return new DefaultPooledObject<>(bean);
    }

    /**
     * 钝化一个对象,也可以理解为反初始化
     *
     * @throws Exception 异常
     */
    @Override
    public void passivateObject(PooledObject<FileDownloader> pooledObject) throws Exception {

    }

    /**
     * 验证对象是否可用
     *
     * @param pooledObject 池化对象
     */
    @Override
    public boolean validateObject(PooledObject<FileDownloader> pooledObject) {
        return pooledObject.getObject().getIsActive();
    }
}
